import { defineStore } from 'pinia'
import type { IUserInfo } from '@/types'
import { getUploadToken } from '@/api'

const theme = true // true==light false==dark

const userInfo: IUserInfo = {
    id: -1,
    username: '未登录',
    role_name: '',
    avatar: '',
    status: 0,
    menu: '',
    token: '',
}

const uploadToken: string = ''

export const useStore = defineStore('main', {
    state() {
        return {
            theme: theme,
            collapsed: false,
            userInfo: userInfo,
            uploadToken: uploadToken,
        }
    },
    actions: {
        setTheme(localTheme?: boolean) {
            if (localTheme !== undefined) {
                this.theme = localTheme
            } else {
                this.theme = !this.theme
            }

            document.documentElement.style.colorScheme = this.themeString
            document.body.setAttribute('arco-theme', this.themeString)
            sessionStorage.setItem('theme', JSON.stringify(this.theme))
        },
        loadTheme() {
            const val = sessionStorage.getItem('theme')
            if (val === null) {
                return
            }
            try {
                this.theme = JSON.parse(val)
                this.setTheme(this.theme)
            } catch (e) {
                return
            }
        },
        setCollapsed(collapsed: boolean) {
            this.collapsed = collapsed
        },
        setUserInfo(obj: IUserInfo) {
            this.userInfo = obj
            sessionStorage.setItem('userInfo', JSON.stringify(obj))
        },
        loadUserInfo() {
            const val = sessionStorage.getItem('userInfo')
            if (val === null) {
                return
            }
            try {
                this.userInfo = JSON.parse(val)
            } catch (e) {
                return
            }
        },
        logout() {
            localStorage.removeItem('userInfo')
            this.userInfo = userInfo
        },
        async getUploadTokenAsync() {
            const result = await getUploadToken()
            this.uploadToken = result.data
        },
    },
    getters: {
        themeString(): string {
            return this.theme ? 'light' : 'dark'
        },
        //判断是否登录
        isLogin(): boolean {
            return this.userInfo.id > -1
        },
        //判断是否是超级管理员
        isAdmin(): boolean {
            return this.userInfo.role_name === 'admin'
        },
        //判断是否是普通管理员
        isCommon(): boolean {
            return this.userInfo.role_name === 'common'
        },
        //判断是否是游客
        isVisitor(): boolean {
            return this.userInfo.role_name === 'visitor'
        },
    },
})
